package com.icangya.interceptor;

import com.icangya.DAO.IRoleDao;
import com.icangya.domain.Admin;
import com.icangya.domain.Jurisdiction;
import com.icangya.domain.Role;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;

public class JurisdictionInterceptor extends HandlerInterceptorAdapter{

    private static Logger log = Logger.getLogger(JurisdictionInterceptor.class);

    @Autowired
    private IRoleDao roleDAO;//

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Admin user = (Admin) request.getSession().getAttribute(ADMIN_USER_SESSION);
        if(user == null){
            log.trace("当前没有用户登录。");
            return false;
        }
        String contextPath = request.getContextPath();//获取上下文路径
        String uri = request.getRequestURI().toString();//获取uri
        String method = request.getMethod();//获取请求方法

        if (!"".equals(contextPath)){
            uri = uri.substring(0,uri.length()-contextPath.length());
        }
        boolean success = false;
        String roles = user.getRoles();
        String[] role = roles.split(",");
        if (role.length < 1){
            return success;
        }
        for (int i = 0 ; i < role.length ; i++){
            success = this.myInterceptor(uri,method,success,role[i]);
            if (success){
                break;
            }
        }
        if (!success){
            request.getRequestDispatcher(contextPath+"/userManage/errorPage").forward(request,response);
        }
        return success;
    }

    //多角色检测拦截
    public boolean myInterceptor(String uri,String method,boolean success,String roleId){
        Role role = roleDAO.findRoleByUserID(Long.valueOf(roleId));

        if (role == null){
            return success;
        }
        List<Jurisdiction> jurisdictions = role.getJurisdictions();
        for (Jurisdiction jurisdiction : jurisdictions){
            if (jurisdiction != null){
                if (jurisdiction.getUrl().matches(uri) && jurisdiction.getMethod().equals(method)){
                    success = true;
                    return success;
                }
                if (success){
                    return success;
                }
            }
        }
        return success;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
